package com.itheima.pay.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("easy")
public class EasyPayController {

    @Autowired
    Config config;


    @GetMapping("/alipaytest")
    public AlipayTradePrecreateResponse alipaytest(String orderNo) {
        // 1. 设置参数（全局只需设置一次） -- 项目启动时初始化
        Factory.setOptions(config);

        try {
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
                    .preCreate("餐掌柜-餐饮消费",
                            orderNo, "0.01");

            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
                System.out.println(response.getHttpBody());
                return response;
            } else {
                System.err.println("调用失败，原因：" + response.msg + "，" + response.subMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @GetMapping("query")
    public AlipayTradeQueryResponse query(String orderNo) {

        // 1. 设置参数（全局只需设置一次） -- 项目启动时初始化
        Factory.setOptions(config);

        try {
            return Factory.Payment.Common().query(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("refund")
    public AlipayTradeRefundResponse refund(String orderNo, String refundMoney) {
        // 1. 设置参数（全局只需设置一次） -- 项目启动时初始化
        Factory.setOptions(config);
        try {
            AlipayTradeRefundResponse response = Factory.Payment.Common().refund(orderNo, refundMoney);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}